package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
)

func main() {
	url := "https://www.huya.com/index.php?m=LiveList&do=getTmpLiveByPage&gameId=1663&tmpId=116&page=1"
	//爬取页面所有所有信息
	result, err := httpGet1(url)
	if err != nil {
		fmt.Println("get err", err)
	}

	//解析编译正则

	num := make(chan int)
	ret := regexp.MustCompile(`"screenshot":"(?s:(.*?))"`)
	//提取图片url
	alls := ret.FindAllStringSubmatch(result, -1)

	//主播昵称

	ret1 := regexp.MustCompile(`"nick":"(?s:(.*?))",`)

	alls1 := ret1.FindAllStringSubmatch(result, -1)

	n := len(alls)

	nikeNames := make([]string, 0)
	for _, nikeName := range alls1 {
		nikeNames = append(nikeNames, nikeName[1])
	}
	imgUrls := make([]string, 0)
	for _, imgUrl := range alls {
		imgUrls = append(imgUrls, strings.Replace(imgUrl[1], "\\", "", -1))
	}

	for i, name := range nikeNames {
		go saveImg1(i, imgUrls[i], unToCh(name), num)
		//go saveImg1(i,imgUrls[i],strconv.Itoa(i),num)
	}

	for i := 0; i < n; i++ {
		fmt.Printf("——第%d张图片下载完成——\n", <-num)
	}
}
func saveImg1(idx int, url, nikeName string, num chan int) {
	path := "D:/imgs/" + nikeName + ".jpg"
	//file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, os.ModePerm)
	file, err := os.Create(path)
	if err != nil {
		fmt.Println("creat err", err)
	}
	defer file.Close()

	resp, err1 := http.Get(url)
	if err1 != nil {
		fmt.Println("save err", err1)
		return
	}
	defer resp.Body.Close()
	buf := make([]byte, 4096)

	for {
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		file.Write(buf[:n])
	}
	num <- idx + 1
}
func unToCh(un string) (ch string) {
	sUnicodev := strings.Split(un, "\\u")
	for _, v := range sUnicodev {

		ret1 := regexp.MustCompile(`^[0000-FFFF]+$`)

		a := ret1.FindAllStringSubmatch(v, -1)

		n := len(a)

		if n == 0 {
			ch += v
			continue
		}

		if len(v) != 4 {
			ch += v
			continue
		}
		temp, err := strconv.ParseInt(v, 16, 32)
		if err != nil {
			panic(err)
		}
		ch += fmt.Sprintf("%c", temp)
	}
	return
}

//获取一个网页的所有内容
func httpGet1(url string) (result string, err error) {
	resp, err1 := http.Get(url)
	if err1 != nil {
		err = err1
		return
	}
	defer resp.Body.Close()
	buf := make([]byte, 4096)

	for {
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		result += string(buf[:n])
	}
	return
}
